<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//include("../../services/resize-class.php");
include("../../services/config/connection.php");
class CommonUtilities {
	
	public $vehicle_id ;
	public $errors ;
    public function __construct() {

    }
	
	public function file_extension($filename)
	{
		return end(explode(".", $filename));
	}
	
    public function upload($id) 
	{
		$this->vehicle_id  = $id;
		
		if (isset($_FILES['file_upload'])) {
			
			for ($i = 0; $i < count($_FILES['file_upload']['name']); $i++) {
				if ($_FILES['file_upload']['name'][$i]) {
					$file_temp = $_FILES['file_upload']['tmp_name'][$i];
					$file_name = $_FILES['file_upload']['name'][$i];
					$db_path_image = "services/upload_image/";
					$db_path_pdf= "services/upload_pdf/";
					
					$file_path_image = "../../".$db_path_image;
					$file_path_pdf = "../../".$db_path_pdf;
					
					if (self::file_extension($file_name) == "pdf")
					{
						$new_file_name = uniqid("auto").".pdf";
						$filestatus = move_uploaded_file($file_temp,$file_path_pdf.$new_file_name);
						if(!file_exists($file_path_pdf.$file_name)){
							if(!$filestatus){
								 $success = "false";
								 //array_push($errors,"Upload failed. Please try again.");
							}else {
								$success = "true";
							}
							//self::create_thumbnail($file_path_image."pdf/pdf.png",$file_path_pdf."thump_pdf.jpg",50,40);
							$db_info = self::inserinto_database($db_path_pdf.$new_file_name, $db_path_pdf."thump_pdf.jpg",$db_path_pdf."thump_pdf.jpg");
						}
						else {
							$success = "false";
							//array_push($errors,"File already exists on server.");
						}
					}
					else
					{
						$new_file_name = uniqid("auto").".jpg";
						$filestatus = move_uploaded_file($file_temp,$file_path_image.$new_file_name);
						if(!file_exists($file_path_image.$file_name)) {
							if(!$filestatus) {
								 $success = "false";
								 //array_push($errors,"Upload failed. Please try again.");
							} else {
								$success = "true";
							}
				
							//$resizeObj = new resize($file_path_image.$new_file_name);
							// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
							//$resizeObj -> resizeImage(600, 500, 'crop');
							// *** 3) Save image
							//$resizeObj -> saveImage($file_path_image."crop/crop_".$new_file_name, 100);
							//unset($resizeObj);
							self::create_thumbnail($file_path_image.$new_file_name,$file_path_image."crop/crop_".$new_file_name,600,500);
							self::create_thumbnail($file_path_image.$new_file_name,$file_path_image."thumps/thump_".$new_file_name,50,40);
							$db_info = self::inserinto_database($db_path_image.$new_file_name, $db_path_image."thumps/thump_".$new_file_name, $db_path_image."crop/crop_".$new_file_name);
						} else {
							$success = "false";
							//array_push($this->errors,"File already exists on server.");
						}
					}
				}
				
			}
			
		} else {
			echo "File is empty";
		}
		self::return_result();
			
    }
    
	private function inserinto_database($filestr, $thumpstr, $cropstr)
	{
	
		/*define( "DATABASE_SERVER", "localhost" );
		define( "DATABASE_USERNAME", "autogator" );
		define( "DATABASE_PASSWORD", "123456" );
		define( "DATABASE_NAME", "autogator-demo" );
	
		//connect to the database
		$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD) or die(mysql_error());
	
		//select the database
		mysql_select_db( DATABASE_NAME );*/
		
		$lastResult;
		
		$my_insert = "INSERT INTO vehicle_image (  `image_url` , `vehicle_id`, `thump_url`, `crop_url`  ) VALUES ('".$filestr. "',".$this->vehicle_id.",'" .$thumpstr. "','".$cropstr."')";  
		$my_insert = mysql_query($my_insert) or die("Query ERROR");
		$result_sel = mysql_insert_id();
		$lastResult->imageUrl = $filestr;
		$lastResult->thumpUrl = $thumpstr;
		$lastResult->corpUrl = $cropstr;
		$lastResult->imageID = $result_sel;
    	$lastResult->vehID = $this->vehicle_id;
		return $lastResult;
	
	
	}
	
	private function create_thumbnail($infile,$outfile,$maxw,$maxh,$stretch = FALSE) 
	{
	  clearstatcache();
	  if (!is_file($infile)) {
	    trigger_error("Cannot open file: $infile",E_USER_WARNING);
	    return FALSE;
	  }
	  if (is_file($outfile)) {
	      trigger_error("Output file already exists: $outfile",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  $functions = array(
	    'image/png' => 'ImageCreateFromPng',
	    'image/jpeg' => 'ImageCreateFromJpeg',
	  );
	 
	  // Add GIF support if GD was compiled with it
	  if (function_exists('ImageCreateFromGif')) { $functions['image/gif'] = 'ImageCreateFromGif'; }
	 
	  $size = getimagesize($infile);
	 
	  // Check if mime type is listed above
	  if (!$function = $functions[$size['mime']]) {
	      trigger_error("MIME Type unsupported: {$size['mime']}",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  // Open source image
	  if (!$source_img = $function($infile)) {
	      trigger_error("Unable to open source file: $infile",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  $save_function = "image" . strtolower(substr(strrchr($size['mime'],'/'),1));
	 
	  // Scale dimensions
	  list($neww,$newh) = self::scale_dimensions($size[0],$size[1],$maxw,$maxh,$stretch);
	 
	  if ($size['mime'] == 'image/png') {
	    // Check if this PNG image is indexed
	    $temp_img = imagecreatefrompng($infile);
	    if (imagecolorstotal($temp_img) != 0) {
	      // This is an indexed PNG
	      $indexed_png = TRUE;
	    } else {
	      $indexed_png = FALSE;
	    }
	    imagedestroy($temp_img);
	  }
	 
	  // Create new image resource
	  if ($size['mime'] == 'image/gif' || ($size['mime'] == 'image/png' && $indexed_png)) {
	    // Create indexed 
	    $new_img = imagecreate($neww,$newh);
	    // Copy the palette
	    imagepalettecopy($new_img,$source_img);
	 
	    $color_transparent = imagecolortransparent($source_img);
	    if ($color_transparent >= 0) {
	      // Copy transparency
	      imagefill($new_img,0,0,$color_transparent);
	      imagecolortransparent($new_img, $color_transparent);
	    }
	  } else {
	    $new_img = imagecreatetruecolor($neww,$newh);
	  }
	 
	  // Copy and resize image
	  imagecopyresampled($new_img,$source_img,0,0,0,0,$neww,$newh,$size[0],$size[1]);
	 
	  // Save output file
	  if ($save_function == 'imagejpeg') {
	      // Change the JPEG quality here
	      if (!$save_function($new_img,$outfile,75)) {
	          trigger_error("Unable to save output image",E_USER_WARNING);
	          return FALSE;
	      }
	  } else {
	      if (!$save_function($new_img,$outfile)) {
	          trigger_error("Unable to save output image",E_USER_WARNING);
	          return FALSE;
	      }
	  }
	 
	  // Cleanup
	  imagedestroy($source_img);
	  imagedestroy($new_img);
	 
	  return TRUE;
	}
	// Scales dimensions
	private function scale_dimensions($w,$h,$maxw,$maxh,$stretch = FALSE) {
	    if (!$maxw && $maxh) {
	      // Width is unlimited, scale by width
	      $newh = $maxh;
	      if ($h < $maxh && !$stretch) { $newh = $h; }
	      else { $newh = $maxh; }
	      $neww = ($w * $newh / $h);
	    } elseif (!$maxh && $maxw) {
	      // Scale by height
	      if ($w < $maxw && !$stretch) { $neww = $w; }
	      else { $neww = $maxw; }
	      $newh = ($h * $neww / $w);
	    } elseif (!$maxw && !$maxh) {
	      return array($w,$h);
	    } else {
	      if ($w / $maxw > $h / $maxh) {
	        // Scale by height
	        if ($w < $maxw && !$stretch) { $neww = $w; }
	        else { $neww = $maxw; }
	        $newh = ($h * $neww / $w);
	      } elseif ($w / $maxw <= $h / $maxh) {
	        // Scale by width
	        if ($h < $maxh && !$stretch) { $newh = $h; }
	        else { $newh = $maxh; }
	        $neww = ($w * $newh / $h);
	      }
	    }
	    return array(round($neww),round($newh));
	}
	
	private function return_result()
	{
		$query_data = "SELECT * FROM vehicle_image WHERE vehicle_id='".$this->vehicle_id."'" ;
        $result_data = mysql_query($query_data) or die("Query ERROR5");
       $result = '';
       while ($row =  mysql_fetch_object($result_data))
       {
          	$result .= '<div><div  style="background-color:white; border:#c2c2c2 solid 1px; margin:5px; width:60px; height:50px; text-align: center; float:left;border-width:1px;border-style:solid;border-color:white;   line-height: 35px; font-size: 1em;"><img style=" margin-top: 5px " src=../../'. $row->thump_url .'></div></div>';
		}
		echo $result;
	}
}
?>
